<?php

namespace app\api\controller\v2;

use app\api\model\Mobile as MobileModel;
use app\common\model\Alipay;
use app\common\model\Wxpay;
use EasyWeChat\Factory;
use think\facade\Db;
use think\facade\Log;
use think\Request;

/**
 * 话费充值
 */
class Mobile extends \app\BaseController
{
    private $settle_discount_slow = 100;  // 【慢充】结算折扣：代理商与平台的折扣
    private $settle_discount_slow_all = [100, 100, 100, 100];  // 【慢充】结算折扣：代理商与平台的折扣，区分运营商
    private $sale_discount_slow = 100;    // 【慢充】销售折扣：代理商给用户的折扣 $settle_discount_slow < $sale_discount_slow
    private $settle_discount_fast = 100;  // 【快充】结算折扣：代理商与平台的折扣
    private $settle_discount_fast_all = [100, 100, 100, 100];  // 【快充】结算折扣：代理商与平台的折扣，区分运营商
    private $sale_discount_fast = 100;    // 【快充】销售折扣：代理商给用户的折扣 $settle_discount_fast < $sale_discount_fast
    private $slow_status = 0;
    private $fast_status = 0;
    private $error = '';

    protected $middleware = [
        \app\middleware\ApiChannel::class,
        \app\middleware\ApiUserAuthV2::class => ['except' => ['phoneInfo']],
    ];

    protected function initialize()
    {
//        $this->request->servType = PRODUCT_MOBILE_SERV;
//        $this->request->servName = '话费';
        parent::initialize();
    }


    /**
     * 初始化折扣信息
     */
    private function init($request)
    {
        $discount = Db::name('channel_serv_discount')
            ->field('value, sub_type')
            ->where('channel_id', $request->agentChannel['id'])
            ->where('serv_type', PRODUCT_MOBILE_SERV)
            ->where('state', 1)
            ->column('value', 'sub_type');
        if (empty($discount[1]) && empty($discount[2])) {
            $this->error = '渠道未启用';
            return false;
        }

        // $agent = Db::name('agent')
        //     ->field('mobile_discount_slow, mobile_discount_fast')
        //     ->where('id', $request->agentChannel['agent_id'])
        //     ->find();
        $config = Db::name('agent_service_config')
            ->field('discount_slow, discount_fast, discount_slow_all, discount_fast_all')
            ->where('agent_id', $request->agentChannel['agent_id'])
            ->where('serv_type', PRODUCT_MOBILE_SERV)
            ->find();

        if (!empty($discount[1])) {
            $this->slow_status = 1;
            $this->settle_discount_slow = $config['discount_slow'];
            $this->settle_discount_slow_all = json_decode($config['discount_slow_all'], true);
            // $this->sale_discount_slow = max($discount[1], $agent['mobile_discount_slow']);
            $this->sale_discount_slow = $discount[1]; // 可以亏本卖
        }
        if (!empty($discount[2])) {
            $this->fast_status = 1;
            $this->settle_discount_fast = $config['discount_fast'];
            $this->settle_discount_fast_all = json_decode($config['discount_fast_all'], true);
            // $this->sale_discount_fast = max($discount[2], $agent['mobile_discount_fast']);
            $this->sale_discount_fast = $discount[2]; // 可以亏本卖
        }
    }

    /**
     * 获取配置
     */
    public function getSetting(Request $request)
    {
        $res = $this->init($request);
        if (false === $res) {
            return fail($this->error);
        }

        $filename = root_path() . 'data/mobileSupplierPriority.json';
        $data = file_get_contents($filename);
        $data = json_decode($data, true) ?? [];

        $tabList = [];
        if ($this->slow_status == 1) {
            $this->sale_discount_slow = floatval($this->sale_discount_slow);
            $tabList[] = [
                'name' => $this->sale_discount_slow . '折慢充',
                'isFast' => 0,
                'discount' => $this->sale_discount_slow,
                'amountList' => [
                    50 => empty($data['other_slow'][50]) ? 0 : 1,
                    100 => empty($data['other_slow'][100]) ? 0 : 1,
                    200 => empty($data['other_slow'][200]) ? 0 : 1,
                ],
            ];
        }
        if ($this->fast_status == 1) {
            $this->sale_discount_fast = floatval($this->sale_discount_fast);
            $tabList[] = [
                'name' => $this->sale_discount_fast . '折快充',
                'isFast' => 1,
                'discount' => $this->sale_discount_fast,
                'amountList' => [
                    50 => empty($data['other_fast'][50]) ? 0 : 1,
                    100 => empty($data['other_fast'][100]) ? 0 : 1,
                    200 => empty($data['other_fast'][200]) ? 0 : 1,
                ],
            ];
        }

        $amountConfig = [];
        $fields = [
            'yidong_fast', 'liantong_fast', 'dianxin_fast', 'other_fast',
            'yidong_slow', 'liantong_slow', 'dianxin_slow', 'other_slow',
        ];
        foreach ($fields as $field) {
            $amountConfig[$field][50] = empty($data[$field][50]) ? 0 : 1;
            $amountConfig[$field][100] = empty($data[$field][100]) ? 0 : 1;
            $amountConfig[$field][200] = empty($data[$field][200]) ? 0 : 1;
        }

        return success('获取成功', [
            'tabList' => $tabList,
            'amountConfig' => $amountConfig,
            'agentChannel' => $request->agentChannel,
        ]);
    }

    /**
     * 下单
     */
    public function createOrder(Request $request)
    {
        $res = $this->init($request);
        if (false === $res) {
            return fail($this->error);
        }

        $params = $this->formatOrderParams($request);
        if (false === $params) {
            return fail($this->error);
        }

        $model = new MobileModel();
        $res = $model->create($params);
        if (false === $res) {
            return fail($model->getError());
        }
        $orderId = $res['orderId'];
        unset($res);

        return success('操作成功', [
            'order_id' => $orderId,
            'order_type' => 'mobile',
        ]);
    }

    private function formatOrderParams($request)
    {
        $params = input('post.');
        if (empty($params['mobile'])) {
            $this->error = '手机号码不能为空';

            return false;
        }
        if (!checkMobile($params['mobile'])) {
            $this->error = '手机号码格式有误';

            return false;
        }
        if (empty($params['amount'])) {
            $this->error = '充值面额不能为空';

            return false;
        }

        $ispType = getMobileIsp($params['mobile']); // 1移动 2联通 3电信 -1其他
        $params['settle_type'] = $request->agentChannel['settle_type'];
        if (!empty($params['is_fast'])) {
            // 快充
            $params['sale_discount'] = $this->sale_discount_fast;
            // 结算价格区分运营商
            $params['settle_discount'] = $this->settle_discount_fast_all[$ispType] ?? $this->settle_discount_fast;
            $orderType = 2;
        } else {
            // 慢充
            $params['sale_discount'] = $this->sale_discount_slow;
            // 结算价格区分运营商
            $params['settle_discount'] = $this->settle_discount_slow_all[$ispType] ?? $this->settle_discount_slow;
            $orderType = 1;
        }

        // 筛选话费供应商 -- start
        // 指定的供应商
        $agentId = $request->agentChannel['agent_id'];
        $usedSupplierIds = Db::name('agent_mobile_supplier')
            ->where('agent_id', $agentId)
            ->column('mobile_supplier_id');
        $map = [
            1 => 'yidong',
            2 => 'liantong',
            3 => 'dianxin',
            -1 => 'other',
        ];
        // $ispType = getMobileIsp($params['mobile']);
        $fieldName = $map[$ispType];
        if ($orderType == 1) {
            $fieldName .= '_slow';
        } else {
            $fieldName .= '_fast';
        }
        $filename = root_path() . '/data/mobileSupplierPriority.json';
        $priority = file_get_contents($filename);
        $priority = json_decode($priority, true);
        if (empty($priority) || empty($priority[$fieldName][$params['amount']])) {
            $this->error = '充值面额维护中';

            return false;
        }
        $tmp = $priority[$fieldName][$params['amount']];
        // todo 待优化
        $supplier = [];
        foreach ($tmp as $id => $num) {
            if (!in_array($id, $usedSupplierIds)) {
                continue;
            }
            $supplier = array_merge($supplier, array_fill(0, $num, $id));
        }
        if (empty($supplier)) {
            $this->error = '充值通道维护中';

            return false;
        }
        $max = count($supplier) - 1;
        $index = random_int(0, $max);
        $mobileSupplierId = $supplier[$index];
        unset($supplier);
        unset($priority);
        // 筛选话费供应商 -- end

        $params['agent_id'] = $request->agentChannel['agent_id'];
        $params['channel_id'] = $request->agentChannel['id'];
        $params['user_id'] = $request->user['id'];
        $params['mobile_supplier_id'] = $mobileSupplierId;
        $params['ext_data'] = json_encode(['bizOrigin' => $params['bizOrigin']??''],JSON_UNESCAPED_UNICODE);

        return $params;
    }

    /**
     * 订单取消.
     */
    public function cancel()
    {
        $orderId = input('post.order_id');
        $payLog = Db::name('pay_log')
            ->field('id, status')
            ->where('order_id', $orderId)
            ->find();
        if (empty($payLog) || $payLog['status'] == 3) {
            return success('取消成功');
        }

        if ($payLog['status'] == 2) {
            return fail('订单已经支付，无法取消');
        }

        Db::startTrans();
        try {
            Db::name('pay_log')
                ->where('id', $payLog['id'])
                ->update([
                    'status' => 3,
                    'remark' => '支付取消',
                ]);
            Db::name('mobile_order')
                ->where('order_id', $orderId)
                ->update([
                    'status' => '3',
                    'remark' => '支付取消',
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('取消失败：' . $e->getMessage() . $e->getLine());
        }

        return success('取消成功');
    }

    /**
     * 订单列表
     */
    public function orderList(Request $request)
    {
        $where = [
            'agent_id' => $request->agentChannel['agent_id'],
            'user_id' => $request->user['id'],
            'status' => 2,
            'order_type' => input('order_type', 1),
        ];

        $list = Db::name('mobile_order')
            ->field('sub_order_id as order_id, mobile, amount, sale_price,
            supplier_status as status, created_at, refund_status, order_type')
            ->where($where)
            ->order('id desc')
            ->paginate([
                'page' => input('page', 1),
                'list_rows' => input('list_rows', 10),
            ])->toArray();
        foreach ($list['data'] as $k => $v) {
            if ($v['status'] < 2) {
                $list['data'][$k]['status'] = 2;
            }
        }

        return success('操作成功', $list);
    }

    /**
     * 手机号码查询.
     */
    public function phoneInfo()
    {
        $mobile = input('post.mobile');
        if (empty($mobile)) {
            return fail('请输入手机号码');
        }
        if (!checkMobile($mobile)) {
            return fail('手机号码格式有误');
        }

        $key = 'mobile_isp_cache_' . $mobile;
        $val = cache($key);
        if ($val) {
            return success('操作成功', $val);
        }

        $api = Db::name('mobile_supplier')
            ->where('code', 'quanmama')
            ->where('is_deleted', 0)
            ->find();
        if (empty($api)) {
            return success('', null);
        }
        $model = new \api\Quanmama($api);
        $info = $model->phoneInfo($mobile);
        $data = $info['data'] ?? null;
        if ($data) {
            cache($key, $data, 300);
        }

        return success('操作成功', $data);
    }

    /**
     * 获取客服链接.
     */
    public function getCustomerServiceUrl(Request $request)
    {
        $url = Db::name('agent_config')
            ->where('agent_id', $request->agentChannel['agent_id'])
            ->value('customer_service_url');
        // if (empty($url)) {
        //     $url = 'https://tb.53kf.com/code/client/47906e25cefde3aaf82ad360af29d8e47/3';
        // }

        return success('操作成功', [
            'url' => $url,
        ]);
    }
}
